package top.zsyle.sycc.mq.consumer;


import bo.CourseOrderPayBo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zsyle.sycc.domain.PayOrder;
import top.zsyle.sycc.exception.GlobalException;
import top.zsyle.sycc.exception.GlobalExceptionEnum;
import top.zsyle.sycc.service.IPayOrderService;
import top.zsyle.sycc.utils.AssertUtil;

import java.nio.charset.StandardCharsets;

@RocketMQMessageListener(
        consumerGroup = "course-order-pay-consumer-group",
        topic = "course-order-pay-topic",
        selectorExpression = "course-order-pay-tag"
)
@Component
@Slf4j
public class CourseOrderPayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    /**
     * ACK机制：
     * 有异常：失败，重新发送消息（默认16次）
     * 没有异常：成功
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body.length == 0){
            // 1.应该记录进入异常的次数，如果超过三次，那么应该通知管理员，手动处理
            log.error("支付消费发生异常，异常原因为：消息信息为空！");
            throw new GlobalException(GlobalExceptionEnum.ERROR);
        }
        //校验参数 判断支付单是否已存在该订单号
        CourseOrderPayBo courseOrderPayBo = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderPayBo.class);
        String orderNo = courseOrderPayBo.getOrderNo();
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
//        AssertUtil.isNull(payOrder,GlobalExceptionEnum.ERROR);
        if (payOrder != null){
            log.error("支付服务消费课程订单时，订单已存在！订单号为：{}",orderNo);
            return;
        }
        //保存支付单 t_pay_order
        payOrderService.insertByInfo(courseOrderPayBo);
    }

}
